<script setup lang="ts">
import { onMounted, ref } from 'vue';
import MSvgIcon from '@/libs/SvgIcon';

import type { MessageProps, MessageType } from './types';

const props = withDefaults(defineProps<MessageProps>(), {
  duration: 2000
});

const animationDuration = '0.5s';

const styles: {
  [key in MessageType]: {
    icon: string;
    fillClass: string;
    textClass: string;
    containerClass: string;
  };
} = {
  warn: {
    icon: 'warn',
    fillClass: 'fill-warn-300',
    textClass: 'text-warn-300',
    containerClass:
      'bg-warn-100 border-warn-200 hover:shadow-lg hover:shadow-warn-100'
  },
  error: {
    icon: 'error',
    fillClass: 'fill-error-300',
    textClass: 'text-error-300',
    containerClass:
      'bg-error-100 border-error-200 hover:shadow-lg hover:shadow-error-100'
  },
  success: {
    icon: 'success',
    fillClass: 'fill-success-300',
    textClass: 'text-success-300',
    containerClass:
      'bg-success-100 border-success-200 hover:shadow-lg hover:shadow-success-100'
  }
};

const isMessageVisible = ref<boolean>(false);

onMounted(() => {
  isMessageVisible.value = true;
  setTimeout(() => {
    isMessageVisible.value = false;

    setTimeout(
      () => {
        if (props.destroy) {
          props.destroy();
        }
      },
      parseFloat(animationDuration) * 1000
    );
  }, props.duration);
});

defineOptions({ name: 'MMessage' });
</script>

<template>
  <Transition name="message">
    <div
      v-if="isMessageVisible"
      :class="styles[props.type].containerClass"
      class="fixed top-[20px] left-1/2 z-50 flex min-w-[420px] -translate-x-1/2 cursor-pointer items-center rounded-sm border px-3 py-1.5"
    >
      <MSvgIcon
        :name="styles[props.type].icon"
        :fillClass="styles[props.type].fillClass"
        class="mr-1.5 h-1.5 w-1.5"
      />
      <span class="text-sm" :class="styles[props.type].textClass">{{
        props.content
      }}</span>
    </div>
  </Transition>
</template>

<style lang="css" scoped>
.message-enter-active,
.message-leave-active {
  transition: all v-bind(animationDuration);
}

.message-enter-from,
.message-leave-to {
  opacity: 0;
  transform: translate3d(0, -100px, 0);
}
</style>
